package com.gjt.serverSocket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;

/**
 * Created with Intel IDEA.
 * 提供单个文件的http 服务器
 *
 * @Auther: gjt
 * @Date: 2024/5/11 8:53
 */
public class SingleFileHttpServer {
    private static final Logger logger = Logger.getLogger("requests.log");

    // 内容
    private  byte[] content;
    // http 头部
    private  byte[] header;
    // 端口
    private int port;
    // 编码
    private  String encoding;

    public SingleFileHttpServer(String data, String encoding, String mimeType, int port) {

    }

    public SingleFileHttpServer(byte[] data, String encoding, String mimeType, int port) {
        this.content = data;
        this.port = port;
        this.encoding = encoding;
        String header = "HTTP/1.0 200 OK\r\n"
                + "Server: OneFile: " + this.content.length + "\r\n"
                + "Content-length: " + mimeType + "; charset=" + encoding + "\r\n";
        this.header = header.getBytes(Charset.forName("US-ASCII"));
    }

    public void start() {
        ExecutorService pool = Executors.newFixedThreadPool(100);
        try (ServerSocket server = new ServerSocket(this.port)) {
            logger.info("Accepting connections on port " + server.getLocalPort());
            logger.info("Data to be sent:");
            logger.info(new String(this.content, encoding));

            while (true) {
                try {
                    Socket accept = server.accept();
//                    pool.submit(new HTTPHandle(connection));

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {

        }
    }

    private class HTTPHandler implements Callable<Void> {

        private final Socket connection;

        public HTTPHandler(Socket connection) {
            this.connection = connection;
        }

        @Override
        public Void call() throws Exception {
            try {
                BufferedWriter bufWriter = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
                BufferedReader bufRead = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                // 只读取第一行，这是我们需要的全部内容
                StringBuilder request = new StringBuilder(80);
                while(true){

                }
            }catch (IOException e){
                e.printStackTrace();
            }


            return null;
        }
    }
}
